package com.inspection.operator;

import com.inspection.common.QuartzManager;
import com.inspection.job.HostRequestJob;
import com.inspection.job.HttpRequestJob;
import com.inspection.model.App;
import com.inspection.model.AppStatus;
import com.inspection.model.Host;
import com.inspection.model.HostInfo;
import com.inspection.utils.AppConfig;
import net.sf.ehcache.CacheManager;
import net.sf.ehcache.Ehcache;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.jdom2.Document;
import org.jdom2.Element;
import org.jdom2.input.SAXBuilder;
import org.quartz.JobDataMap;
import org.quartz.SchedulerException;

import javax.servlet.ServletContextEvent;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.Socket;
import java.text.ParseException;
import java.util.*;
import java.util.List;

/**
 * Created by zhujun on 2015-6-4.
 */
public class XmlAnalysis {

    /**
     * 初始化系统的常量
     */
    public static void initConstant(ServletContextEvent servletContextEvent) {
        HashMap apps = new HashMap();
        HashMap hosts = new HashMap();

        SAXBuilder builder = new SAXBuilder();
        try {
            Document doc = builder.build(servletContextEvent.getServletContext().getRealPath("/WEB-INF/config.xml"));
            Element rootElement = doc.getRootElement();

            AppConfig.appkey = rootElement.getAttribute("appkey").getValue();

            List<Element> apps_childs = rootElement.getChild("apps").getChildren();
            Element child = null;
            for (int i = 0; i < apps_childs.size(); i++) {
                child = apps_childs.get(i);
                App app = new App();
                app.setName(child.getAttribute("name").getValue());
                app.setUrl(child.getAttribute("url").getValue());
                app.setRegular(child.getAttribute("regular").getValue());
                apps.put(app.getUrl(), app);
            }

            List<Element> hosts_childs = rootElement.getChild("hosts").getChildren();
            for (int i = 0; i < hosts_childs.size(); i++) {
                child = hosts_childs.get(i);
                Host host = new Host();
                host.setName(child.getAttribute("name").getValue());
                host.setIp(child.getAttribute("ip").getValue());
                host.setPort(child.getAttribute("port").getIntValue());
                host.setRegular(child.getAttribute("regular").getValue());
                hosts.put(host.getIp(), host);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        AppConfig.apps = apps;
        AppConfig.hosts = hosts;

        /**
         * 获取缓存对象
         */
        CacheManager cacheManager = CacheManager.create(servletContextEvent.getServletContext().getRealPath("/WEB-INF/ehcache.xml"));
        AppConfig.cache = cacheManager.getEhcache("APPCACHE");

    }

    /**
     * 进行Quartz进行任务调度的设置
     */
    public static void initQuartz() {
        String jobGroup = null;
        String triggerGroup = null;

        jobGroup = "app_jobGroup";
        triggerGroup = "app_triggerGroup";
        HashMap apps = AppConfig.apps;
        Iterator iter = apps.entrySet().iterator();
        while (iter.hasNext()) {
            Map.Entry entry = (Map.Entry) iter.next();
            Object key = entry.getKey();
            App app = (App)entry.getValue();
            try {
                JobDataMap jobDataMap = new JobDataMap();
                jobDataMap.put("key",key.toString());
                jobDataMap.put("value",app);
                QuartzManager.addJob(key.toString(), jobGroup, key.toString(), triggerGroup, HttpRequestJob.class, app.getRegular(), jobDataMap);
            } catch (SchedulerException e) {
                e.printStackTrace();
            } catch (ParseException e) {
                e.printStackTrace();
            }
        }

        HashMap hosts = AppConfig.hosts;
        Iterator iter_hosts = hosts.entrySet().iterator();
        while (iter_hosts.hasNext()) {
            Map.Entry entry = (Map.Entry) iter_hosts.next();
            Object key = entry.getKey();
            Host host = (Host)entry.getValue();
            try {
                JobDataMap jobDataMap = new JobDataMap();
                jobDataMap.put("key",key.toString());
                jobDataMap.put("value",entry.getValue());
                QuartzManager.addJob(key.toString(), "host_jobGroup", key.toString(), "host_triggerGroup", HostRequestJob.class, host.getRegular(),jobDataMap);
            } catch (SchedulerException e) {
                e.printStackTrace();
            } catch (ParseException e) {
                e.printStackTrace();
            }
        }


    }

    /**
     * 获取主机的信息
     *
     * @param ip
     * @param port
     */
    public static HostInfo getHostInfo(String ip,int port){

        Socket socket = null;
        try {
            socket = new Socket(ip, port);

            ObjectInputStream ois = new ObjectInputStream(socket.getInputStream());
            HostInfo hostInfo = (HostInfo)ois.readObject();

            return hostInfo;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return  null;
    }

    /**
     *
     * 根据HOST,类型，显示图例
     *
     * @param host
     * @param type
     */
    public static void showImageForHost(String host, String type,HttpServletResponse response) {

       /* String filePath = AppConfig.storage+"/"+host+"/"+type+".rrd";

        Long lasttime = Tools.getLastUnix();

        if(type.equals("mem_used")){
            //内存使用情况
            try {
                RrdDb rrdDb = new RrdDb(filePath);
                RrdGraphDef graphDef = new RrdGraphDef(lasttime-3600,lasttime);
                graphDef.datasource("Used", filePath, "Used", "AVERAGE");
                graphDef.line("Used", new Color(0xFF, 0, 0), null, 1);
                graphDef.setShowSignature(false);
                RrdGraph rrdGraph = new RrdGraph(graphDef);
                response.getOutputStream().write(rrdGraph.getPNGBytes());
            } catch (IOException e) {
                e.printStackTrace();
            } catch (RrdException e) {
                e.printStackTrace();
            }
        }*/



    }

    /**
     * 获取http状态
     *
     * @param url
     * @return
     */
    public static AppStatus getHttpInfo(String url) {

        AppStatus appStatus = new AppStatus();

        CloseableHttpClient httpclient = HttpClients.createDefault();
        HttpGet httpGet = new HttpGet(url);
        CloseableHttpResponse response = null;
        try {
            response = httpclient.execute(httpGet);
            appStatus.setStatusLine(response.getStatusLine().toString());
        } catch (IOException e) {
            e.printStackTrace();
        }

        return appStatus;
    }



}
